package com.baizw.cultivation.module.admin.controller;

import com.baizw.cultivation.common.response.ResultBean;
import com.baizw.cultivation.common.search.CommonSearch;
import com.baizw.cultivation.module.admin.entity.ResourceEntity;
import com.baizw.cultivation.module.admin.entity.vo.ResourceTreeSelect;
import com.baizw.cultivation.module.admin.entity.vo.UserMenu;
import com.baizw.cultivation.module.admin.service.ResourceService;
import com.baizw.cultivation.util.PermissionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 资源控制器
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年06月08日 17:52
 */
@RestController
@Api(tags = "资源控制器")
@RequestMapping("/api/resource")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @GetMapping("/list/{userId}")
    @ApiOperation("资源列表")
    public ResultBean listResource(@PathVariable Long userId) {
        List<UserMenu> resourceEntityList = resourceService.listResource(userId);
        return ResultBean.ok().setResult(resourceEntityList);
    }

    @PostMapping("/list/page")
    @ApiOperation("资源列表分页")
    public ResultBean pageResource(@RequestBody CommonSearch search) {
        return ResultBean.ok().setResult(resourceService.listTreeBySearch(search));
    }

    @GetMapping("/list/select")
    @ApiOperation("已登录用户树状下拉菜单")
    public ResultBean selectTree() {
        List<ResourceTreeSelect> resourceEntityList = resourceService.selectTree();
        return ResultBean.ok().setResult(resourceEntityList);
    }

    @GetMapping("/list/nav")
    @ApiOperation("当前已登录用户菜单列表")
    public ResultBean loadUserNav() {
        List<UserMenu> resourceEntityList = resourceService.listResourceTree();
        return ResultBean.ok().setResult(resourceEntityList);
    }

    @ApiOperation("新增/更新资源")
    @PostMapping("/save_or_update")
    @CacheEvict(cacheNames = {"sys_resource", "MENU_SELECT"}, allEntries = true)
    public ResultBean saveResource(@RequestBody ResourceEntity resourceEntity) {
        // 根据actions转化二进制权限
        resourceEntity.setPermission(PermissionUtil.buildPermissionString(resourceEntity.getActions()));
        return ResultBean.isTrue(resourceService.saveOrUpdate(resourceEntity));
    }

    @ApiOperation("删除资源")
    @DeleteMapping("/delete/{resourceIds}")
    @CacheEvict(cacheNames = {"sys_resource", "MENU_SELECT"}, allEntries = true)
    public ResultBean deleteById(@PathVariable Long[] resourceIds) {
        return ResultBean.isTrue(resourceService.removeByIds(Arrays.asList(resourceIds)));
    }
}
